package com.ecommerce.service;

import com.ecommerce.dao.CartDAO;
import com.ecommerce.dao.ProductDAO;
import com.ecommerce.model.CartItem;
import com.ecommerce.model.Product;
import com.ecommerce.util.InputUtil;
import java.util.List;

public class CartService {
    private CartDAO cartDAO;
    private ProductDAO productDAO;

    public CartService() {
        this.cartDAO = new CartDAO();
        this.productDAO = new ProductDAO();
    }

    public boolean addToCart(int userId) {
        System.out.println("\n=== 添加商品到购物车 ===");

        // 显示所有上架商品
        ProductService productService = new ProductService();
        productService.browseProductsForCustomer();

        int productId = InputUtil.getIntInput("请输入要添加的商品ID: ");
        int quantity = InputUtil.getIntInput("请输入数量: ");

        if (quantity <= 0) {
            System.out.println("数量必须大于0！");
            return false;
        }

        // 检查商品是否存在且库存充足
        Product product = productDAO.getActiveProductById(productId);
        if (product == null) {
            System.out.println("商品不存在或已下架！");
            return false;
        }

        if (product.getStockQuantity() < quantity) {
            System.out.println("库存不足！当前库存: " + product.getStockQuantity());
            return false;
        }

        CartItem cartItem = new CartItem(userId, productId, quantity);
        boolean success = cartDAO.addToCart(cartItem);

        if (success) {
            System.out.println("成功添加到购物车！");
        } else {
            System.out.println("添加到购物车失败！");
        }

        return success;
    }

    public void viewCart(int userId) {
        List<CartItem> cartItems = cartDAO.getCartItemsByUserId(userId);

        System.out.println("\n=== 我的购物车 ===");
        if (cartItems.isEmpty()) {
            System.out.println("购物车为空");
        } else {
            double total = 0;
            for (CartItem item : cartItems) {
                System.out.println("ID: " + item.getId() + " | " + item);
                total += item.getSubtotal();
            }
            System.out.println("--------------------------------");
            System.out.printf("总计: ¥%.2f\n", total);
        }
        System.out.println("===============");
    }

    public void updateCartItemQuantity(int userId) {
        System.out.println("\n=== 修改购物车商品数量 ===");
        viewCart(userId);

        int cartItemId = InputUtil.getIntInput("请输入要修改的购物车商品ID: ");

        // 验证该购物车项属于当前用户
        CartItem cartItem = cartDAO.getCartItemById(cartItemId);
        if (cartItem == null || cartItem.getUserId() != userId) {
            System.out.println("购物车商品不存在！");
            return;
        }

        int newQuantity = InputUtil.getIntInput("请输入新的数量: ");

        if (newQuantity <= 0) {
            System.out.println("数量必须大于0！");
            return;
        }

        // 检查库存
        Product product = productDAO.getActiveProductById(cartItem.getProductId());
        if (product.getStockQuantity() < newQuantity) {
            System.out.println("库存不足！当前库存: " + product.getStockQuantity());
            return;
        }

        boolean success = cartDAO.updateCartItemQuantity(cartItemId, newQuantity);
        if (success) {
            System.out.println("数量更新成功！");
        } else {
            System.out.println("数量更新失败！");
        }
    }

    public void removeFromCart(int userId) {
        System.out.println("\n=== 从购物车删除商品 ===");
        viewCart(userId);

        int cartItemId = InputUtil.getIntInput("请输入要删除的购物车商品ID: ");

        // 验证该购物车项属于当前用户
        CartItem cartItem = cartDAO.getCartItemById(cartItemId);
        if (cartItem == null || cartItem.getUserId() != userId) {
            System.out.println("购物车商品不存在！");
            return;
        }

        // 确认删除
        String confirm = InputUtil.getStringInput("确认删除？(y/N): ");
        if ("y".equalsIgnoreCase(confirm)) {
            boolean success = cartDAO.deleteCartItem(cartItemId);
            if (success) {
                System.out.println("删除成功！");
            } else {
                System.out.println("删除失败！");
            }
        } else {
            System.out.println("取消删除");
        }
    }

    public void clearCart(int userId) {
        System.out.println("\n=== 清空购物车 ===");

        List<CartItem> cartItems = cartDAO.getCartItemsByUserId(userId);
        if (cartItems.isEmpty()) {
            System.out.println("购物车已经是空的！");
            return;
        }

        // 确认清空
        String confirm = InputUtil.getStringInput("确认清空整个购物车？(y/N): ");
        if ("y".equalsIgnoreCase(confirm)) {
            boolean success = cartDAO.clearUserCart(userId);
            if (success) {
                System.out.println("购物车已清空！");
            } else {
                System.out.println("清空购物车失败！");
            }
        } else {
            System.out.println("取消清空");
        }
    }

    public void manageCart(int userId) {
        while (true) {
            System.out.println("\n=== 购物车管理 ===");
            System.out.println("1. 查看购物车");
            System.out.println("2. 添加商品到购物车");
            System.out.println("3. 修改商品数量");
            System.out.println("4. 从购物车删除商品");
            System.out.println("5. 清空购物车");
            System.out.println("6. 返回上级菜单");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    viewCart(userId);
                    break;
                case 2:
                    addToCart(userId);
                    break;
                case 3:
                    updateCartItemQuantity(userId);
                    break;
                case 4:
                    removeFromCart(userId);
                    break;
                case 5:
                    clearCart(userId);
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    public List<CartItem> getCartItems(int userId) {
        return cartDAO.getCartItemsByUserId(userId);
    }

    public double calculateCartTotal(int userId) {
        List<CartItem> cartItems = cartDAO.getCartItemsByUserId(userId);
        double total = 0;
        for (CartItem item : cartItems) {
            total += item.getSubtotal();
        }
        return total;
    }

    public boolean isCartEmpty(int userId) {
        List<CartItem> cartItems = cartDAO.getCartItemsByUserId(userId);
        return cartItems.isEmpty();
    }
}
